<template>
  <div class="app-container">
    <el-row :gutter="10">
      <!--树结构-->
      <el-col :span="isHide ? 1 : 6" :xs="24" class="relative">
        <div class="app-container-tree-border">
          <project-tree-select-inner class="cd-mb8" :projectId="projectId" @changeProject="changeProject" />
          <el-input class="cd-mb8" v-model="filterText" placeholder="请输入(红色表示未计量过)" clearable size="small"
            prefix-icon="el-icon-search" />
          <el-tree class="input-tree" v-loading="treeLoading" :data="treeList" :props="defaultProps" ref="tree"
            node-key="id" highlight-current @node-click="handleNodeClick" :filter-node-method="filterNode">
            <div slot-scope="{node, data}" class="custom-tree-node"
              :class="{ 'red': data.type == 'zd' && data.jlg == 0 }" :title="node.label" v-text="node.label"></div>
          </el-tree>
          <div class="tree-hide-button iconfont" :class="isHide ? 'icon-xiangyou' : 'icon-xiangzuo'"
            @click="() => { isHide = !isHide }">
          </div>
        </div>
      </el-col>
      <el-col :span="isHide ? 23 : 18" :xs="24">
        <div class="app-container-table-border" v-show="treeInfo.type == 'zd'">
          <div class="header-title">
            <span>第</span>
            <el-select class="cd-ml8 cd-mr8" v-model="queryParams.qsId" placeholder="" size="mini" style="width: 60px;"
              @change="qsChange">
              <el-option :class="{ 'red': item.hasJl == 0 }" v-for="item in qsOptions" :key="item.qsId"
                :label="item.settleIndex" :value="item.qsId"></el-option>
            </el-select>
            <span>期计量列表</span>
          </div>
          <el-row class="mb8 top-right-btn small-line-height">
            <el-button v-if="canUpdate" type="success" plain size="mini" :loading="buttonLoading" @click="submitForm"
              v-hasPermi="['cm:bsSettle:edit']" :disabled="!canOperation()">保存</el-button>
            <el-button v-else type="primary" plain size="mini" @click="onUpdate" v-hasPermi="['cm:bsSettle:add']"
              :disabled="!canOperation()">编辑</el-button>
            <el-button type="primary" plain size="mini" @click="onUploadFile()"
              :disabled="!canOperation()">附件管理</el-button>
          </el-row>
          <el-form ref="form" :model="form" :rules="rules" label-width="0px">
            <el-table border stripe v-loading="loading" :data="form.dataList" :summary-method="getSummaries"
              show-summary :max-height="tableHeight">
              <el-table-column label="清单类别" align="center" property="sheetTypeName" min-width="140"
                show-overflow-tooltip>
                <template slot-scope="scope">
                  <span>{{ scope.row.sheetTypeName || "-" }}</span>
                </template>
              </el-table-column>
              <el-table-column label="规格型号" align="center" property="sheetFeaturesName" min-width="120"
                show-overflow-tooltip>
                <template slot-scope="scope">
                  <span>{{ scope.row.sheetFeaturesName || "-" }}</span>
                </template>
              </el-table-column>
              <el-table-column label="单位" align="center" property="sheetUnit" min-width="100">
                <template slot-scope="scope">
                  <span>{{ scope.row.sheetUnit || "-" }}</span>
                </template>
              </el-table-column>
              <el-table-column label="数量" header-align="center" align="right" property="initRongliang" min-width="120">
                <template slot-scope="scope">
                  <span>{{ scope.row.initRongliang || "-" }}</span>
                </template>
              </el-table-column>
              <el-table-column label="变更数量" header-align="center" align="right" property="chgRongliang" min-width="120">
                <template slot-scope="scope">
                  <span>{{ scope.row.chgRongliang || "-" }}</span>
                </template>
              </el-table-column>
              <el-table-column label="单价(元)" header-align="center" align="right" property="initDanjia" min-width="120">
                <template slot-scope="scope">
                  <span>{{ scope.row.initDanjia || "-" }}</span>
                </template>
              </el-table-column>
              <el-table-column label="报税总价(元)" header-align="center" align="right" property="initZongjia"
                min-width="120">
                <template slot-scope="scope">
                  <span>{{ scope.row.initZongjia || "-" }}</span>
                </template>
              </el-table-column>
              <el-table-column label="变更后总价(元)" header-align="center" align="right" property="chgZongjia"
                min-width="120">
                <template slot-scope="scope">
                  <span>{{ scope.row.chgZongjia || "-" }}</span>
                </template>
              </el-table-column>
              <el-table-column label="税率(%)" header-align="center" align="right" property="sheetTaxRate"
                min-width="100">
                <template slot-scope="scope">
                  <span>{{ scope.row.sheetTaxRate || "-" }}</span>
                </template>
              </el-table-column>
              <el-table-column label="计量数量" header-align="center" align="right" prop="measurementQuantity"
                min-width="140">
                <template slot-scope="scope">
                  <el-form-item v-if="canUpdate && scope.row.initDanjia"
                    :prop="'dataList.' + scope.$index + '.measurementQuantity'" :rules="rules.measurementQuantity">
                    <el-input-number size="mini" v-model="scope.row.measurementQuantity" placeholder="" :precision="4"
                      :controls="false" style="width: 100%;"
                      @blur="measurementQuantityChange(scope.row)"></el-input-number>
                  </el-form-item>
                  <span v-else>{{ scope.row.measurementQuantity || "-" }}</span>
                </template>
              </el-table-column>
              <el-table-column label="合价" header-align="center" align="right" prop="totalPrice" min-width="120">
                <template slot-scope="scope">
                  <el-form-item v-if="canUpdate && scope.row.initDanjia"
                    :prop="'dataList.' + scope.$index + '.totalPrice'" :rules="rules.totalPrice">
                    <el-input-number size="mini" v-model="scope.row.totalPrice" placeholder="" :precision="2"
                      :controls="false" style="width: 100%;" />
                  </el-form-item>
                  <span v-else>{{ scope.row.totalPrice || "-" }}</span>
                </template>
              </el-table-column>
              <el-table-column label="累计计量数量" header-align="center" align="right"
                min-width="120">
                <template slot-scope="scope">
                  <span>{{ computlj(scope.row) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="未计量数量" header-align="center" align="right" prop="remainingQuantity"
                min-width="120" />
            </el-table>
          </el-form>
        </div>
        <div class="app-container-table-border" v-show="treeInfo.type == 'bd'">
          <el-table border stripe v-loading="loading" :data="form.dataList" :summary-method="getSummaries2" show-summary
            :max-height="tableHeight2" :span-method="spanMethod">
            <el-table-column label="站点名称" align="center" property="zdName" min-width="160" show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ scope.row.zdName || "-" }}</span>
              </template>
            </el-table-column>
            <el-table-column label="实际合同额" align="center" property="sjhte" min-width="140" show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ scope.row.sjhte || "0.00" }}</span>
              </template>
            </el-table-column>
            <el-table-column label="期数" align="center" property="qs" min-width="140" show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ scope.row.qs || "-" }}</span>
              </template>
            </el-table-column>
            <el-table-column label="本期计量金额" align="center" property="bqjlje" min-width="140">
              <template slot-scope="scope">
                <span>{{ scope.row.bqjlje || "0.00" }}</span>
              </template>
            </el-table-column>
            <el-table-column label="累计计量金额" align="center" property="jlje" min-width="140">
              <template slot-scope="scope">
                <span>{{ scope.row.jlje || "0.00" }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
    </el-row>
    <file-upload-view ref="fileUploadViewRef" :moduleKey="'bsSettle'" :disabled="!canOperation()" />
  </div>
</template>

<script>
import { queryBdTree } from "@/api/base/bsBd";
import { listBsQs } from "@/api/cm/bsQs";
import { queryPeriodMeasurementList, queryPeriodMeasurementListByBd, updatePeriodMeasurementList } from "@/api/cm/periodMeasurement";
import { getApprovalStatus } from "@/api/cm/baContractSheets";
import { queryReportStatus } from "@/api/cm/reportForm";
import { mapGetters } from "vuex";
import FileUploadView from '@/components/FileUpload/FileUploadView.vue';
import decimal from "@/utils/big-decimal";
export default {
  name: "BsSettle",
  components: {
    FileUploadView
  },
  data () {
    // 计量数量
    const measurementQuantityChange = (rule, value, callback) => {
      if (!value) {
        return callback();
      }
      // 计算计量数量不可超过总数量
      // 拆分获取index
      const field = rule.field;
      const arr = field.split('.');
      if (arr.length == 3) {
        const index = arr[1];
        // 总剩余数量
        const oldRemainingQuantity = this.form.dataList[index].oldRemainingQuantity;
        if (Number(value) > Number(oldRemainingQuantity)) {
          this.form.dataList[index].measurementQuantity = 0;
          this.measurementQuantityChange(this.form.dataList[index]);
          return callback(new Error('计量已超量!'));
        }
      }
      callback();
    };
    return {
      filterText: '',
      isHide: false,
      treeList: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      treeLoading: false,
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      qsOptions: [],
      // 计量单管理表格数据
      dataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      canUpdate: false,
      // 查询参数
      queryParams: {
        qsId: undefined,
        zdId: undefined,
        bdId: undefined
      },
      reportStatus: '',// 报表状态
      contractSheetsStatus: '',// 报表状态
      projectId: undefined,
      // 表单参数
      form: {
        dataList: []
      },
      treeInfo: {
        type: 'zd'
      },
      // 表单校验
      rules: {
        measurementQuantity: [{ validator: measurementQuantityChange, trigger: 'blur' }]
      },
      tableHeight: document.documentElement.scrollHeight - 220,
      tableHeight2: document.documentElement.scrollHeight - 130,

    };
  },
  // 监听顶部全局下拉
  computed: {
    ...mapGetters(["sysProjectId", "sysProjectList"])
  },
  watch: {
    sysProjectId (newVal, oldVal) {
      // 系统顶部选中项目变化
      this.changeProject(newVal);
    },
    filterText (val) {
      this.$refs.tree.filter(val);
    }
  },
  created () {
    this.changeProject();
  },
  methods: {
    computlj (item) {
      let sl = Number.parseFloat(item.initRongliang || 0);
      let chgsl = Number.parseFloat(item.chgRongliang || 0);
      let wjlsl = Number.parseFloat(item.remainingQuantity || 0);
      return decimal.subtract(decimal.add(sl, chgsl, 3), wjlsl, 3);
    },
    changeProject (projectId = this.sysProjectId) {
      this.projectId = projectId;
      this.projectChangeResetQuery();
      this.getBdTree();
    },
    filterNode (value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    getBdTree () {
      this.treeLoading = true;
      queryBdTree({ projectId: this.projectId, hasJl: 1 }).then(response => {
        this.treeList = response.data;
      }).finally(() => {
        this.treeLoading = false;
      });
    },
    handleNodeClick (data) {
      if (data.type == 'zd') {
        this.treeInfo = data;
        this.queryParams.zdId = data.id;
        this.queryParams.bdId = data.parentId;
        if (this.queryParams.bdId == this.queryParams.oldBdId) {
          this.qsChange();
        } else {
          // this.getQs();
        }
        this.getQs();
        this.getContractSheetsStatus();
        this.queryParams.oldBdId = data.parentId;

      } else if (data.type == 'bd') {
        this.treeInfo = data;
        this.queryParams.bdId = data.id;
        this.getListByBd();
        // this.$modal.msgWarning("请选择站点");
        // this.queryParams.zdId = null;
        // this.$refs.tree.setCurrentKey(data.children[0].id);
      }
    },
    projectChangeResetQuery () {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        qsId: undefined,
        bdId: undefined,
        zdId: undefined,
      };
      this.total = 0;
      this.form.dataList = [];
      this.reportStatus = '';
      this.qsOptions = [];
    },
    // 获取期数
    getQs () {
      const queryParams = {
        bdId: this.queryParams.bdId,
        zdId: this.queryParams.zdId,
        pageNum: 1,
        pageSize: 100,
        jlType: 1 // 1 中间计量 2 其他计量
      };
      listBsQs(queryParams).then(response => {
        this.qsOptions = response.rows;
        if (this.qsOptions.length > 0) {
          // 默认期数
          let qsInfo = this.qsOptions.find(item => item.currentFlag == 1);
          if (!qsInfo) {
            qsInfo = this.qsOptions[this.qsOptions.length - 1];
          }
          this.queryParams.qsId = qsInfo.qsId;
          this.queryParams.qs = qsInfo.qs;
          this.qsChange();
        } else {
          this.queryParams.qsId = null;
          this.queryParams.qs = null;
          this.reportStatus = '';
          this.total = 0;
          this.form.dataList = [];
        }
      });
    },
    qsChange () {
      const info = this.qsOptions.find(item => item.qsId == this.queryParams.qsId);
      this.queryParams.qs = info.settleIndex;
      this.handleQuery();
      this.getReportStatus();
    },

    /** 查询计量单管理列表(站点) */
    getList () {
      this.loading = true;
      this.canUpdate = false;
      const info = {
        qsId: this.queryParams.qsId,
        zdId: this.queryParams.zdId,
        bdId: this.queryParams.bdId,
        // settleIndex: this.queryParams.settleIndex,
      };
      queryPeriodMeasurementList(info).then(response => {
        this.form.dataList = response.data;
        if (this.form.dataList.length > 0) {
          this.form.dataList.forEach(item => {
            item['oldRemainingQuantity'] = decimal.add(item.remainingQuantity, item.measurementQuantity,4);
          });
        }
        this.loading = false;
      });
    },
    getListByBd () {
      this.loading = true;
      this.canUpdate = false;
      const info = {
        bdId: this.queryParams.bdId,
      };
      queryPeriodMeasurementListByBd(info).then(response => {
        this.form.dataList = response.data;
        this.loading = false;
      });
    },
    // 表单重置
    reset () {
      this.form = {
        projectId: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 获取报表状态 00 未审核 33 已驳回  这两个状态时可编辑
    getReportStatus () {
      const query = {
        bdId: this.queryParams.bdId,
        qsId: this.queryParams.qsId
      };
      queryReportStatus(query).then(res => {
        const { status } = res.data;
        this.reportStatus = status;
      });

    },
    // 合同清单审批状态
    getContractSheetsStatus () {
      const query = {
        bdId: this.queryParams.bdId,
        zdId: this.queryParams.zdId
      };
      getApprovalStatus(query).then(res => {
        const { approvalStatus, chgApprovalStatus } = res.data;
        this.contractSheetsStatus = approvalStatus;
      });
    },
    getSummaries (param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        if (index === 6 || index === 7 || index === 10) {
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return decimal.add(prev, curr, 2);
              } else {
                return decimal.round(prev);
              }
            }, 0);
            sums[index] += '';
          } else {
            sums[index] = '';
          }
        }
      });

      return sums;
    },
    // getSummaries2 (param) {
    //   const { columns, data } = param;
    //   const sums = [];
    //   columns.forEach((column, index) => {
    //     if (index === 0) {
    //       sums[index] = '合计';
    //       return;
    //     }
    //     if (index === 1 || index === 3) {
    //       const values = data.map(item => Number(item[column.property]));
    //       if (!values.every(value => isNaN(value))) {
    //         sums[index] = values.reduce((prev, curr) => {
    //           const value = Number(curr);
    //           if (!isNaN(value)) {
    //             return decimal.add(prev, curr, 2);
    //           } else {
    //             return decimal.round(prev);
    //           }
    //         }, 0);
    //         sums[index] += '';
    //       } else {
    //         sums[index] = '';
    //       }
    //     }
    //   });
    //
    //   return sums;
    // },
    getSummaries2 (param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        // 只对特定列（如 index === 1 或 3）进行合计
        if ([1, 3, 4].includes(index)) {
          let sum = 0;
          // 遍历时跳过被合并的行（例如 zdName 相同但不是第一行）
          data.forEach((item, idx) => {
            // 对于第1列和第4列：只累加主行
            if (index === 1 || index === 4) {
              const isMainRow = idx === 0 || data[idx - 1]?.zdName !== item.zdName;
              if (!isMainRow) return;
            }
            // 对于第3列：所有行都累加
            const key = column.property;
            const value = Number(item[key]);

            if (!isNaN(value)) {
              // sum += value; // 使用普通加法测试
              sum = decimal.add(sum, value, 2); // 高精度可选
            }
          });
          sums[index] = isNaN(sum) ? '0.00' : Number.parseFloat(sum).toFixed(2);
        } else {
          sums[index] = '';
        }
      });

      return sums;
    },
    measurementQuantityChange (row) {
      // 计算合价
      row.totalPrice = decimal.multiply(row.initDanjia, row.measurementQuantity, 2);
      // 计算剩余数量
      row.remainingQuantity = decimal.subtract(row.oldRemainingQuantity, row.measurementQuantity, 4);
      return row;
    },
    /** 新增按钮操作 */
    onUpdate () {
      this.canUpdate = true;
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          const info = {
            qsId: this.queryParams.qsId,
            zdId: this.queryParams.zdId,
            bdId: this.queryParams.bdId,
            measurementBos: this.form.dataList
          };
          updatePeriodMeasurementList(info).then(response => {
            this.$modal.msgSuccess("保存成功");
            this.canUpdate = false;
            this.getList();
          }).finally(() => {
            this.buttonLoading = false;
          });
        }
      });
    },
    // 附件上传
    onUploadFile () {
      const info = {
        businessId: this.queryParams.zdId,
        subBusinessId: this.queryParams.qsId,
      };
      this.$refs.fileUploadViewRef.init(info);
    },
    spanMethod ({ row, column, rowIndex, columnIndex }) {
      // 获取当前行数据和下一行数据（用于判断是否连续）
      const currentRow = this.form.dataList[rowIndex];
      const nextRow = this.form.dataList[rowIndex + 1];

      // 合并“站点名称”列（columnIndex === 0）
      // if (columnIndex === 0) {
      //   let count = 0;
      //   for (let i = rowIndex; i < this.form.dataList.length; i++) {
      //     if (this.form.dataList[i].zdName === currentRow.zdName) {
      //       count++;
      //     } else {
      //       break;
      //     }
      //   }
      //
      //   if (rowIndex === 0 || this.form.dataList[rowIndex - 1].zdName !== currentRow.zdName) {
      //     return { rowspan: count, colspan: 1 };
      //   } else {
      //     return { rowspan: 0, colspan: 0 };
      //   }
      // }

      // 合并“实际合同额”列（columnIndex === 1）
      if (columnIndex === 0 || columnIndex === 1 || columnIndex === 4) {
        let count = 0;
        for (let i = rowIndex; i < this.form.dataList.length; i++) {
          if (
            this.form.dataList[i].sjhte === currentRow.sjhte &&
            this.form.dataList[i].zdName === currentRow.zdName &&
            this.form.dataList[i].jlje === currentRow.jlje
          ) {
            count++;
          } else {
            break;
          }
        }

        // 合并“累计计量金额”列（columnIndex === 4）
        // if (columnIndex === 4) {
        //   let count = 0;
        //   for (let i = rowIndex; i < this.form.dataList.length; i++) {
        //     if (
        //       this.form.dataList[i].sjhte === currentRow.sjhte &&
        //       this.form.dataList[i].zdName === currentRow.zdName
        //     ) {
        //       count++;
        //     } else {
        //       break;
        //     }
        //   }

        if (
          rowIndex === 0 ||
          this.form.dataList[rowIndex - 1].sjhte !== currentRow.sjhte ||
          this.form.dataList[rowIndex - 1].zdName !== currentRow.zdName
        ) {
          return { rowspan: count, colspan: 1 };
        } else {
          return { rowspan: 0, colspan: 0 };
        }
      }

      // 其他列不合并
      return { rowspan: 1, colspan: 1 };
    },
    // 是否可操作
    canOperation () {
      return this.queryParams.zdId && this.queryParams.qsId && (this.reportStatus == '00' || this.reportStatus == '33') && this.contractSheetsStatus == '22';
    }
  }
};
</script>
<style lang="scss" scoped>
.header-title {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 10px 0;
  font-size: 20px;
  font-weight: 700;
}
</style>
